package com.shenzhen.horselive.ui.fragment;

import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.shenzhen.horselive.Constants;
import com.shenzhen.horselive.R;
import com.shenzhen.horselive.User;
import com.shenzhen.horselive.adapter.LainTongAdapter;
import com.shenzhen.horselive.api.ApiFactory;
import com.shenzhen.horselive.base.BaseFragment;
import com.shenzhen.horselive.beans.AllCityLordBean;
import com.shenzhen.horselive.beans.NewsBean;
import com.shenzhen.horselive.beans.NoticeBean;
import com.shenzhen.horselive.databinding.FragmentLianTongBinding;
import com.shenzhen.horselive.databinding.FragmentLianTongTestBinding;
import com.shenzhen.horselive.databinding.HeadLiantongBinding;
import com.shenzhen.horselive.network.SchedulersCompat;
import com.shenzhen.horselive.presenter.LoadingViewObserver;
import com.shenzhen.horselive.presenter.ViewObserver;
import com.shenzhen.horselive.ui.activity.CityPartnerActivity;
import com.shenzhen.horselive.ui.activity.MapViewActivity;
import com.shenzhen.horselive.ui.activity.NoticesActivity;
import com.shenzhen.horselive.ui.activity.OpenCardActivity;
import com.shenzhen.horselive.ui.activity.PhoneRechargeActivity;
import com.shenzhen.horselive.ui.activity.TestActivity;
import com.shenzhen.horselive.ui.activity.WebActivity;
import com.tencent.tencentmap.mapsdk.maps.CameraUpdate;
import com.tencent.tencentmap.mapsdk.maps.CameraUpdateFactory;
import com.tencent.tencentmap.mapsdk.maps.TencentMap;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptor;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptorFactory;
import com.tencent.tencentmap.mapsdk.maps.model.CameraPosition;
import com.tencent.tencentmap.mapsdk.maps.model.IOverlay;
import com.tencent.tencentmap.mapsdk.maps.model.LatLng;
import com.tencent.tencentmap.mapsdk.maps.model.LatLngBounds;
import com.tencent.tencentmap.mapsdk.maps.model.Marker;
import com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions;

import java.util.ArrayList;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 * Use the {@link LianTongTestFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class LianTongTestFragment extends BaseFragment {

    public static LianTongTestFragment newInstance() {
        LianTongTestFragment fragment = new LianTongTestFragment();
        return fragment;
    }
    FragmentLianTongTestBinding  binding;
    @Override
    protected View getContentView(LayoutInflater inflater, ViewGroup viewGroup) {
        binding = FragmentLianTongTestBinding.inflate(getLayoutInflater(),viewGroup,false);
        initViews();
        return binding.getRoot();
    }

    @Override
    protected void loadDataOnece() {
        super.loadDataOnece();
        initData();
    }

    AllCityLordBean  cityLordBean;
    private void   getAllMastersList()
    {
        ApiFactory.getApiService().allMasterList(User.get().getMyInfo().getToken(),"2")
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new ViewObserver<AllCityLordBean>(this) {
                    @Override
                    protected void onNextInActive(AllCityLordBean allCityLordBean) {
                        if (allCityLordBean.isSuccess())
                        {
                            if (allCityLordBean.getData()!=null)
                            {
                                cityLordBean = allCityLordBean;
                                addMarkToMap(allCityLordBean.getData());
                            }

                        }else
                        {
                            showToast(allCityLordBean.getErrMessage());
                        }
                    }
                });
    }

    private void initData() {
       //加载咨询
       ApiFactory.getApiService().news(User.get().getMyInfo().getToken())
               .compose(SchedulersCompat.applyIoSchedulers())
               .safeSubscribe(new LoadingViewObserver<NewsBean>(this) {
                   @Override
                   protected void onNextInActive(NewsBean newsBean) {
                       if (binding.smartRefresh.isRefreshing())
                       {
                           binding.smartRefresh.finishRefresh();
                       }
                       if (newsBean.isSuccess())
                       {
                           adapter.setNewInstance(newsBean.getData());
                       }else
                       {
                           showToast(newsBean.getErrMessage());
                       }
                   }
               });
//        通知
        ApiFactory.getApiService().noticesList(User.get().getMyInfo().getToken())
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new ViewObserver<NoticeBean>(this) {
                    @Override
                    protected void onNextInActive(NoticeBean noticeBean) {
                        if (noticeBean.isSuccess())
                        {
                           if (noticeBean.getData().size()>0)
                           {
                               binding.viewFlipper.removeAllViews();
                               for (int i = 0; i <noticeBean.getData().size() ; i++) {
                                   if (i==2)
                                   {
                                       //之加载三条
                                       break;
                                   }
                                   View  view
                                           = getLayoutInflater().inflate(R.layout.filp_item_textview,null);
                                   TextView  textView=  view.findViewById(R.id.tv_news);
                                   textView.setText(noticeBean.getData().get(i).getNewsTitle());
                                   binding.viewFlipper.addView(view);
                               }
                           }
                        }
                    }
                });
    }

    /**
     * 添加地图标点
     * @param data
     */
    private void addMarkToMap(List<AllCityLordBean.DataBean> data) {
        //地图正常显示
        BitmapDescriptor custom = BitmapDescriptorFactory.fromResource(R.mipmap.ico_red_qi);
        List<IOverlay> overlays = new ArrayList<>();
       List<LatLng>  latLngList =  new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
          LatLng  latLng =   new LatLng(Double.parseDouble(data.get(i).getLat()), Double.parseDouble(data.get(i).getLng()));
          latLngList.add(latLng) ;
          Marker marker = tencentMap.addMarker(new MarkerOptions(latLng)
                    .icon(custom)
                    .anchor(0.5f, 1)
                    );
            overlays.add(marker);
        }
//        tencentMap.moveCamera(CameraUpdateFactory.newCameraPosition(
//                tencentMap.calculateZoomToSpanLevel(
//                        overlays, latLngList,
//                        10, 10, 10, 10)));
//        tencentMap.moveCamera(CameraUpdateFactory.newLatLngBounds(new LatLngBounds.Builder().include(latLngList).build(),100));
       //展示中国
//        北纬34.322700，  东经108.552500
        LatLng  latLng = new LatLng();
        latLng.latitude = 34.322700;
        latLng.longitude = 108.552500;
        CameraUpdate cameraSigma =
                CameraUpdateFactory.newLatLngZoom(latLng,2.0f);
        tencentMap.moveCamera(cameraSigma); //移动地图

    }

    LainTongAdapter  adapter;
    //初始化views
    private void initViews() {
        binding.recyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new LainTongAdapter(R.layout.item_liantong);
        binding.recyclerview.setAdapter(adapter);
        binding.mapContanier.setScrollView(binding.scrollView);
        tencentMap = binding.mapView.getMap();
        tencentMap.setOnMapLoadedCallback(new TencentMap.OnMapLoadedCallback() {
            public void onMapLoaded() {
                //获取所有的城主
                getAllMastersList();
            }
        });
        tencentMap.setOnMapClickListener(new TencentMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
            //大地图浏览
                MapViewActivity.start(getContext(),cityLordBean);
            }
        });
        binding.imgKaika.setOnClickListener(onClickListener);
        binding.imgHehuo.setOnClickListener(onClickListener);
        binding.imgHuafei.setOnClickListener(onClickListener);
        binding.viewFlipper.setOnClickListener(onClickListener);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                String  id =  LianTongTestFragment.this.adapter.getItem(position).getId()+"";
                if (TextUtils.isEmpty(id))
                    return;
                WebActivity.start(getContext(), Constants.H5_NEWS+"?id="+id,"资讯详情");
            }
        });

//        binding.smartRefresh.setEnableScrollContentWhenLoaded(false);//是否在加载完成时滚动列表显示新的内容
        binding.smartRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                initData();
            }
        });
        binding.smartRefresh.setEnableLoadMore(false);

    }


    TencentMap  tencentMap;
    long  mlasttime;
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            long  nowtime = System.currentTimeMillis();
            if ((nowtime-mlasttime)/1000<1)
                return;
            mlasttime =nowtime;
            switch (v.getId())
            {
                case R.id.img_kaika:
                    startActivity(new Intent(getContext(), OpenCardActivity.class));
                    break;
                case R.id.img_hehuo:
                    //合伙人
                    startActivity(new Intent(getContext(), CityPartnerActivity.class));
                    break;
                case R.id.img_huafei:
                    startActivity(new Intent(getContext(), PhoneRechargeActivity.class));
//                    startActivity(new Intent(getContext(), TestActivity.class));

                    break;
                case R.id.view_flipper:
                    startActivity(new Intent(getContext(), NoticesActivity.class));
                    break;
            }
        }
    };

    @Override
    public void onStart() {
        super.onStart();
       binding.mapView.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        binding.mapView.onResume();
    }





    @Override
    public void onPause() {
        super.onPause();
      binding.mapView.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    binding.mapView.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
     binding.mapView.onDestroy();
    }

    @Override
    public void initImmersionBar() {
        ImmersionBar.with(this)
                .statusBarColor(R.color.white)
                .statusBarDarkFont(true)
                .init();
    }

    @Override
    public boolean immersionBarEnabled() {
        return super.immersionBarEnabled();
    }
}